<template>
  <li>
    <label>
      <!--                                   获取todo的done 判断是否勾选    改变勾选框则执行check方法-->
      <input type="checkbox" :checked="todo.done" @change="check(todo.id)"/>
      <span v-text="todo.title" v-show="!todo.isEdit">xxxxx</span>
      <!--      点击编辑isedit变为true 输入框显现 @blur失去焦点 输入框消失-->
      <input type="text" :value="todo.title" v-show="todo.isEdit" @blur="handleBlur(todo,$event)" ref="inputTitle">
    </label>
    <button class="btn btn-danger" @click="handleDelete(todo.id)">删除</button>
    <button class="btn btn-edit" @click="handleEdit(todo)" v-show="!todo.isEdit">编辑</button>
  </li>
</template>

<script>

export default {
  name: "Item",
  //接收todo信息   接收checkTodo方法
  props: ['todo'],
  methods: {
    //将id传递给app
    check(id) {
      // this.checkTodo(id);
      //触发checkTodo 传递id
      this.$bus.$emit("checkTodo", id)
    },
    handleDelete(id) {
      if (confirm('确定删除吗？')) {
        // this.deleteTodo(id);
        //触发deleteTodo 传递id
        this.$bus.$emit("deleteTodo", id)
      }
    },
    handleEdit(todo) {
      //判断是否有isEdit
      if (Object.prototype.hasOwnProperty.call(todo, 'isEdit')) {
        todo.isEdit = true;
      } else {
        //给todo追加属性
        this.$set(todo, 'isEdit', true)
      }
      //.$nextTick 下一次dom更新结束后执行指定的回调
      this.$nextTick(function () {
        //获取焦点
        this.$refs.inputTitle.focus()
      })

    },
    //失去焦点回调
    handleBlur(todo, e) {
      todo.isEdit = false;
      // 将输入框数据回传
      if (!e.target.value.trim()) {
        return alert('输入不能为空')
      } else {
        this.$bus.$emit('updateTodo', todo.id, e.target.value)
      }
    }
  }
}
</script>

<style scoped>
/*item*/
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}

li label {
  float: left;
  cursor: pointer;
}

li label li input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}

li button {
  float: right;
  display: none;
  margin-top: 3px;
}

li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}

li:hover {
  background-color: #dddddd;
}

li:hover button {
  display: block;
}
</style>
